package sdk.webview.fmc.com.fmcsdk.view;

import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import sdk.webview.fmc.com.fmcsdk.R;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.ToastUtils;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;


/**
 * 修改密码的dialog
 */
public class ChangePasswordDialog extends Dialog {
	private Context context;

	private ClickListenerInterface clickListenerInterface;
    private EditText et_initial_password;
    private EditText et_new_password;
    private EditText et_again_new_password;

    public ChangePasswordDialog(Context context) {
		super(context, R.style.Dialog);
		this.context = context;
	}

	public void forcePasswordChange(boolean b){
		ImageView iv_tips = (ImageView) findViewById(R.id.iv_tips);
    	if (b){
    		iv_tips.setVisibility(View.VISIBLE);
			String s = UserHelper.getSavedUser().getRecord().getPassword();
			TextView tv_title = (TextView) findViewById(R.id.tv_title);

			tv_title.setText(context.getResources().getString(R.string.change_password_title));
			et_initial_password.setText(s);
			this.setCancelable(false);
		}else {
			iv_tips.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.change_password_dialog);

		TextView confirm = (TextView) findViewById(R.id.confirm);
		TextView cancel = (TextView) findViewById(R.id.cancel);
		ImageView iv_tips = (ImageView) findViewById(R.id.iv_tips);
         et_initial_password = (EditText) findViewById(R.id.et_initial_password);
        et_new_password = (EditText) findViewById(R.id.et_new_password);
        et_again_new_password = (EditText) findViewById(R.id.et_again_new_password);
        confirm.setOnClickListener(new clickListener());
        iv_tips.setOnClickListener(new clickListener());
		cancel.setOnClickListener(new clickListener());
		//设置dialog的属性
		Window dialogWindow = getWindow();
	    WindowManager.LayoutParams lp = dialogWindow.getAttributes();
	    DisplayMetrics d = context.getResources().getDisplayMetrics(); // 获取屏幕宽、高
	    lp.width = (int) (d.widthPixels * 0.9);
	    dialogWindow.setAttributes(lp);

	}

	public void setClicklistener(ClickListenerInterface clickListenerInterface) {
		this.clickListenerInterface = clickListenerInterface;
	}

	private class clickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			int id = v.getId();
			if (id==R.id.confirm){
				String oldpsd = et_initial_password.getText().toString().trim();
				String newpsd = et_new_password.getText().toString().trim();
				String chkpsd = et_again_new_password.getText().toString().trim();

				String appName = (String) Utility.getMetaData(context, Constant.APP_NAME);
				String psdLevel = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.PSD_LEVEL, "0");
				if (psdLevel.equals("2")){
					checkPasswordChar(oldpsd, newpsd, chkpsd);
				}else {
					checkPassword(oldpsd, newpsd, chkpsd);
				}
//				if (Constant.APP_NAME_ZSJ.equals(appName)){

//				}else {
//					checkPassword(oldpsd, newpsd, chkpsd);
//				}
			}else if (id == R.id.cancel){
				clickListenerInterface.doCancel();
			}else if (id == R.id.iv_tips){
				ChangePasswordTipsDialog changePasswordTipsDialog = new ChangePasswordTipsDialog(context);
				changePasswordTipsDialog.show();
			}
		}

	}

    /***
     * 校验密码
     */
    private void checkPassword(String oldpsd,String newpsd,String chkpsd) {
		String psdLevel = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.PSD_LEVEL, "0");
		XLog.i("psdLevel--"+psdLevel);
		String s = UserHelper.getSavedUser().getRecord().getPassword();
        //判断旧密码是否输入正确
        if(oldpsd.equals(UserHelper.getSavedUser().getRecord().getPassword())){
            //判断新密码是否一致
            if(newpsd.equals(chkpsd)){
                //change_password Action操作
                if (newpsd.equals(oldpsd)) {//新密码同原密码一致
					ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdequalsodlpsw));
                }else if (newpsd.length()<6) {//低于6位

					if (psdLevel.equals("1")){
						ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdlengtherror8));
						return;
					}
					ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdlengtherror));
                }else {//发送请求修改密码

					//判断强密码和弱密码
					if (psdLevel.equals("1")){
						if (newpsd.length()<8){
							ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdlengtherror8));
							return;
						}
					if (!isContainAll(newpsd)){
						ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdlengtherror_letter));
						return;
					}
					}
//					ToastUtils.showShort(context,"xiugaile");
					clickListenerInterface.doConfirm(oldpsd,newpsd,chkpsd);
                }

            }else {//两次密码不一致
				ToastUtils.showShort(context,context.getResources().getString(R.string.hint_setting_psdisdifferent));
            }
        }else{
			ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdiserror));
        }



    }




	/***
	 * 校验密码
	 */
	private void checkPasswordChar(String oldpsd,String newpsd,String chkpsd) {
		String psdLevel = PreferenceManager.getDefaultSharedPreferences(context).getString(Constant.PSD_LEVEL, "0");
		XLog.i("psdLevel--"+psdLevel);
		String  s = UserHelper.getSavedUser().getRecord().getPassword();
		//判断旧密码是否输入正确
		if(oldpsd.equals(UserHelper.getSavedUser().getRecord().getPassword())){

			if (TextUtils.isEmpty(newpsd)){
				ToastUtils.showShort(context,context.getResources().getString(R.string.hint_setting_input_newpsd));
				return;
			}
			if (TextUtils.isEmpty(chkpsd)){
				ToastUtils.showShort(context,context.getResources().getString(R.string.hint_setting_agine_input_newpsd));
				return;
			}
			//判断新密码是否一致
			if(newpsd.equals(chkpsd)){
				//change_password Action操作
				if (newpsd.equals(oldpsd)) {//新密码同原密码一致
					ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdequalsodlpsw));
				}else if (newpsd.length()<6) {//低于6位
					if (psdLevel.equals("0")){
						ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content1));
						return;
					}
					if (psdLevel.equals("1")){
						ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content2));
						return;
					}
					if (psdLevel.equals("2")){
						ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content3));
						return;
					}
//					ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdlengtherror));
				}else {//发送请求修改密码

					//判断强密码和弱密码
					if (psdLevel.equals("1")){
						if (newpsd.length()<8){
							ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content2));
							return;
						}

							if (!isContainAll(newpsd)){
								ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content2));
								return;
						}
					}

					if (psdLevel.equals("2")){
						if (newpsd.length()<8){
							ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content3));
							return;
						}


							if (!isContainAllChar(newpsd)){
								ToastUtils.showShort(context,context.getResources().getString(R.string.password_change_content3));
								return;
						  }
					}

					clickListenerInterface.doConfirm(oldpsd,newpsd,chkpsd);
				}

			}else {//两次密码不一致
				ToastUtils.showShort(context,context.getResources().getString(R.string.hint_setting_psdisdifferent));
			}
		}else{
			ToastUtils.showShort(context,context.getResources().getString(R.string.msg_setting_psdiserror));
		}



	}


	public interface ClickListenerInterface {

		public void doConfirm(String initialPassword, String newPassword, String againPassword);

		public void doCancel();
	}


	public static boolean isContainAll(String str) {
//		boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
//		boolean isLowerCase = false;//定义一个boolean值，用来表示是否包含字母
//		boolean isUpperCase = false;
//		for (int i = 0; i < str.length(); i++) {
//			if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
//				isDigit = true;
//			} else if (Character.isLowerCase(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
//				isLowerCase = true;
//			} else if (Character.isUpperCase(str.charAt(i))) {
//				isUpperCase = true;
//			}
//		}
//		String regex = "^[a-zA-Z0-9]+$";
//		boolean isRight = isDigit && isLowerCase && isUpperCase && str.matches(regex);
//		return isRight;
		// 检查是否包含至少一个大写字母
		boolean hasUpperCase = str.matches(".*[A-Z].*");
		// 检查是否包含至少一个小写字母
		boolean hasLowerCase = str.matches(".*[a-z].*");
		// 检查是否包含至少一个数字
		boolean hasDigit = str.matches(".*\\d.*");

		// 密码必须同时满足以上三个条件
		return hasUpperCase && hasLowerCase && hasDigit;
	}



	public static boolean isContainAllChar(String str) {
		boolean isDigit = false;//定义一个boolean值，用来表示是否包含数字
		boolean isLowerCase = false;//定义一个boolean值，用来表示是否包含字母
		boolean isUpperCase = false;
		for (int i = 0; i < str.length(); i++) {
			if (Character.isDigit(str.charAt(i))) {   //用char包装类中的判断数字的方法判断每一个字符
				isDigit = true;
			} else if (Character.isLowerCase(str.charAt(i))) {  //用char包装类中的判断字母的方法判断每一个字符
				isLowerCase = true;
			} else if (Character.isUpperCase(str.charAt(i))) {
				isUpperCase = true;
			}
		}
		String regex = "^(?![A-z0-9]+$)(?=.[^%&',;=?$\\x22])(?=.*[a-z])(?=.*[A-Z])(?=.*[0-9]).{8,20}$";
		boolean isRight = isDigit && isLowerCase && isUpperCase && str.matches(regex);
		return isRight;
	}

}
